//
//  DCWBaseRequest.m
//  Meng800
//
//  Created by 姚宗超 on 14/7/19.
//  Copyright (c) 2014年 点财网. All rights reserved.
//

#import "MPHttpRequest.h"
#import "MPError.h"
#import "NSString+Common.h"
#import "MPAppConstant.h"
#import "MKNetworkKit.h"
#import "MPHttpEngine.h"


@implementation MPHttpRequest

/**
 *发送请求
 */
-(void)sendPostRequestWithMethod:(NSString*)method
                           param:(NSDictionary*)param
                      onComplete:(MPRequestComplete) requestComplete
{
    if ([NSString stringIsEmpty:method]) {
        if (requestComplete != nil) {
            // 异常处理
            MPError* error = [MPError errorWithCode:MPErrorCodeGeneralError errorMessage:@"method nil"];
            requestComplete(MPErrorCodeGeneralError, nil, error);
        }
        return;
    }
    NSString* query = [NSString stringWithFormat:@"/%@",method];
    
    [self sendRequestWithParam:param
                           url:query
                     postOrGet:@"POST"
                    onComplete:requestComplete];
}

-(void)sendGetRequestWithMethod:(NSString*)method
                          param:(NSDictionary*)param
                     onComplete:(MPRequestComplete) requestComplete
{
    if ([NSString stringIsEmpty:method]) {
        if (requestComplete != nil) {
            // 异常处理
            MPError* error = [MPError errorWithCode:MPErrorCodeGeneralError errorMessage:@"method nil"];
            requestComplete(MPErrorCodeGeneralError, nil, error);
        }
        return;
    }
    
    NSString* query = [NSString stringWithFormat:@"/%@", method];

    [self sendRequestWithParam:param
                           url:query
                     postOrGet:@"GET"
                    onComplete:requestComplete];
}

-(void)sendRequestWithParam:(NSDictionary*)param
                        url:(NSString*)urlPath
                  postOrGet:(NSString*)postOrGet
                 onComplete:(MPRequestComplete)requestComplete
{
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithDictionary:param];
   
    // 上传
//    NSData* data = [dic objectForKey:@"uploadData"];
//    NSString* fileName = [dic objectForKey:@"fileName"];
//    
//    NSString* finalUrl = [NSString stringWithFormat:@"%@%@", KDCWAPIURL, urlPath];
//    
//    MKNetworkOperation* network = [[MKNetworkOperation alloc] initWithURLString:finalUrl params:dic httpMethod:postOrGet];
//    
//    if (data != nil) {
//        // 上传
//        if (fileName == nil) {
//            fileName = @"dcw-ios.jpg";
//        }
//        [network addData:data forKey:@"file1" mimeType:@"application/octet-stream" fileName:fileName];
//    }
    
    NSString* finalUrl = [NSString stringWithFormat:@"%@%@", kMPAPIURL, urlPath];
    MKNetworkOperation* network = [[MKNetworkOperation alloc] initWithURLString:finalUrl params:dic httpMethod:postOrGet];
    
    id uploadData = [dic objectForKey:@"uploadData"];
    if ([uploadData isKindOfClass:[NSArray class]]) {
        NSArray* dataArray = (NSArray *)uploadData;
        int i = 1;
        for (NSDictionary* dataInfoDic in dataArray) {
            NSData* data = [dataInfoDic objectForKey:@"data"];
            NSString* fileName = [dataInfoDic objectForKey:@"fileName"];
            
            if (data != nil) {
                // 上传
                if (fileName == nil) {
                    fileName = @"dcw-ios.png";
                }
                NSString* field = [NSString stringWithFormat:@"file%d", i++];
//                [network addData:data forKey:field mimeType:@"application/octet-stream" fileName:fileName];
                [network addData:data forKey:field mimeType:@"audio/mpeg" fileName:fileName];
            }
        }
    }
    else
    {
        NSData* data = (NSData *)uploadData;
        NSString* fileName = [dic objectForKey:@"fileName"];
        
        if (data != nil) {
            // 上传
            if (fileName == nil) {
                fileName = @"dcw-ios.png";
            }
//            [network addData:data forKey:@"file1" mimeType:@"application/octet-stream" fileName:fileName];
            [network addData:data forKey:@"file1" mimeType:@"audio/mpeg" fileName:fileName];
        }
    }
    
    if ([dic objectForKey:@"isMultiPartHead"]) { // add by yaozongchao
        network.isMultiPartHead = YES;
    }
    else
    {
        network.isMultiPartHead = NO;
    }
    
    KDLogInfo(@"######################## send data dic:%@\n%@", urlPath, dic);
    [network addCompletionHandler:^(MKNetworkOperation *completedOperation)
     {
         if (requestComplete == nil) {
             return;
         }
         // 网络访问成功
         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
         dispatch_async(queue, ^{
             // 解析数据
             NSDictionary* json = [completedOperation responseJSON];
             KDLogInfo(@"######################## receive data dic:%@\n%@", urlPath, json);
             dispatch_async(dispatch_get_main_queue(), ^{
                 if ([json isKindOfClass:[NSDictionary class]] && json.count>0) {
                     // 看是否出错
                     NSNumber* errorNO = [json objectForKey:@"errno"];
                     if (errorNO.integerValue != MPErrorCodeSuccess) {
                         // 出错啦，取错误信息
                         NSString* errorMsg = [json objectForKey:@"error"];
                         KDLogError(@"ERROR:%@", errorMsg);
                         MPError* e = [MPError errorWithCode:errorNO.integerValue errorMessage:errorMsg];
                         requestComplete(errorNO.integerValue, nil, e);
                     }
                     else {
                         // 接口调用成功
                         requestComplete(MPErrorCodeSuccess, [json objectForKey:@"data"], nil);
                     }
                 }
                 else {
                     // 接口数据异常
                     MPError* e = [MPError errorWithCode:MPErrorCodeServerError errorMessage:@"接口数据异常"];
                     requestComplete(MPErrorCodeServerError, nil, e);
                 }
             });
         });
         
     }
                     errorHandler:^(MKNetworkOperation *completedOperation, NSError *error)
     {
         // 网络访问失败
         KDLogError(@"######################## connect error:%@\n%@", urlPath, error);
         if (requestComplete != nil) {
             MPError* e = [MPError errorWithNSError:error];
             requestComplete(MPErrorCodeNetworkError, nil, e);
         }
     }];
    [[MPHttpEngine sharedInstance] enqueueOperation:network];
}


@end
